package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.AddressBook;
import com.itheima.reggie.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/addressBook")
public class AddressBookController {

    @Autowired
    private AddressBookService addressBookService;

    @PostMapping
    public R saveAddress(@RequestBody AddressBook addressBook){

        addressBook.setUserId(BaseContext.getCurrentId());

        addressBookService.save(addressBook);

        return R.success("保存地址成功");
    }

    @PutMapping("/default")
    public R defaultAddress(@RequestBody AddressBook addressBook){

        LambdaUpdateWrapper<AddressBook> qw = new LambdaUpdateWrapper<>();
        qw.eq(AddressBook::getUserId, BaseContext.getCurrentId());
        qw.set(AddressBook::getIsDefault,0);
        addressBookService.update(qw);

        addressBook.setIsDefault(1);
        addressBookService.updateById(addressBook);

        return R.success(addressBook);
    }

    @GetMapping("/{id}")
    public R getById(@PathVariable Long id){
        AddressBook addressBook = addressBookService.getById(id);
        if (addressBook==null){
            return R.error("查无地址");
        }
        return R.success(addressBook);
    }

    @GetMapping("/default")
    public R getDefault(){
        LambdaQueryWrapper<AddressBook> qw=new LambdaQueryWrapper<>();
        qw.eq(AddressBook::getUserId,BaseContext.getCurrentId());
        qw.eq(AddressBook::getIsDefault,1);
        AddressBook addressBook = addressBookService.getOne(qw);
        if (null==addressBook){
            return R.error("没有找到该对象");
        }
        return R.success(addressBook);
    }

    @GetMapping("/list")
    public R getList(AddressBook addressBook){
        addressBook.setUserId(BaseContext.getCurrentId());
        LambdaQueryWrapper<AddressBook> qw=new LambdaQueryWrapper<>();
        qw.eq(null!=addressBook.getUserId(),AddressBook::getUserId,addressBook.getUserId());
        qw.orderByDesc(AddressBook::getUpdateTime);
        List<AddressBook> list = addressBookService.list(qw);
        return R.success(list);
    }

    @DeleteMapping
    public R delete(@RequestParam List<Long> ids){

        addressBookService.removeByIds(ids);

        return R.success("删除成功");
    }

    @PutMapping
    public R updateAddress(@RequestBody AddressBook addressBook){
        addressBookService.updateById(addressBook);
        return R.success("修改成功");
    }

























}
